from Tool import GrabScreen
import cv2
import time
import numpy as np
from Tool.getkeys import key_check
from Tool import keys
import win32api
import win32con

import random
import math

wait_time = 3
size = [2560, 1080]
# window_size = (0, 0, 1920, 1080)
window_size = (int(2560 / 2 - size[0] * 0.5), int(1080 / 2 - size[1] * 0.5), int(2560 / 2 + size[0] * 0.5),
               int(1080 / 2 + size[1] * 0.5))

lower = np.array([89, 120, 168])
upper = np.array([95, 255, 255])


lower_R = np.array([0, 43, 46])
upper_R = np.array([10, 255, 255])
# origin_state = [size[0] / 2, size[1] / 2]
origin_state = [2560 / 2, 1080 / 2]
paused = False


def find_target(raw_image):
    hsv_image = cv2.cvtColor(raw_image, cv2.COLOR_BGR2HSV)
    hsv_image = cv2.inRange(hsv_image, lower, upper)
    contours, hierarchy = cv2.findContours(hsv_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    if len(contours) > 0:
        # contours = filter(lambda x: cv2.contourArea(x) > 100, contours)
        bbox = list(map(cv2.boundingRect, contours))
        return bbox
    return []


# Counting Down
for i in list(range(wait_time))[::-1]:
    print(i + 1)
    time.sleep(1)
keys = keys.Keys()

while (True):
    keylist = key_check()

    # T to pause the program
    if 'T' in keylist:
        if paused:
            print('Not Paused')
            paused = not (paused)
            time.sleep(1)
        else:
            paused = True
            print("Paused")
            time.sleep(1)
    if not paused:

        screen = GrabScreen.grab_screen(window_size)
        targets = find_target(screen)

        if len(targets) > 0:
            distance = [math.sqrt((d[0] + d[2] / 2 - origin_state[0]) ** 2 + (d[1] + d[3] / 2 - origin_state[1]) ** 2)
                        for d in targets]
            best_index = distance.index(min(distance))
            target = targets[best_index]

            centerx = target[0] + 0.5 * target[2]
            centery = target[1] + 0.5 * target[3]

            # Function

            if abs(int(centerx) - 1280) < 0.4 * target[2] and abs(int(centery - 540)) < 0.4 * target[3]:
                keys.directMouse(buttons=keys.mouse_lb_press)
                time.sleep(0.001)
                keys.directMouse(buttons=keys.mouse_lb_release)
                time.sleep(0.001)
                continue
            else:
                win32api.mouse_event(win32con.MOUSEEVENTF_MOVE, int(centerx) - 1280, int(centery - 540))
                # win32api.mouse_event(win32con.MOUSEEVENTF_MOVE, random.randint(-3,3), random.randint(-3,3))
                continue
